/**
 * Created by lixinghan on 2016/11/11.
 */

var http = require('http');
var fs = require('fs');
var url = require('url');
var querystring = require('querystring');
var server = http.createServer(httpRequest);
var mime = require('mime');

function httpRequest(request,resport){
    var filePath = '';
    if(request.url == '/'){
        if(request.method == 'POST'){
            var data = '';
            request.on('data',function(chunk){
                data += chunk;
            });
            request.on('end', function () {
               var user = querystring.parse(data);

                fs.readFile(__dirname+'/tsconfig.json','utf-8',function(error,data){
                    if(error){
                        return;
                    }
                    var data = JSON.parse(data);
                    var isSame = false;
                    for (var i = 0; i < data.userList.length; i++){
                        if(data.userList[i].username == user.username){
                            isSame = true;
                            break;
                        }
                    }
                    if(isSame){
                        console.log('名字被占用了！');
                    }else {
                        data.userList.push(user);
                        fs.writeFile(__dirname + '/tsconfig.json',JSON.stringify(data));
                    }
                });

            });
        }
        filePath = __dirname + '/public/index.html';
    }else{
        filePath = __dirname + '/public/' + request.url;
    }
    readFile(resport,filePath);
}

function  readFile(resport,filePath){
    fs.exists(filePath,function(exists){
       if(exists){
           fs.readFile(filePath,function(error,data){
              if(error){
                  return;
              }
               resport.writeHead(200,{'Content-type':mime.lookup(filePath)});
               resport.end(data);
           });
       }else {
           resport.writeHead(404,{'Content-type':'text/plain'});
           resport.end('sorry!');
       }
    });
}

server.listen(8080,function(){
    console.log('服务器启动成功!');
});